package com.cpecc.controller.system;

import com.cpecc.manager.system.*;
import com.cpecc.manager.wuzi.*;
import com.cpecc.model.system.Dep;
import com.cpecc.model.system.Email;
import com.cpecc.model.system.LDAP;
import com.cpecc.model.system.User;
import com.cpecc.model.wuzi.WuZi;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.wisteria.framework.web.APIResult;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping(value = "/system")
public class SystemController {
	
	@Autowired
	private DepManager depManager;
	
	@Autowired
	private RoleManager roleManager;
	
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private WuZiManager wuZiManger;
	
	@Autowired
	private EmailManager emailManager;
	
	@Autowired
	private LDAPManager ldapManager;
	
	@Autowired
	private ToDoManager toDoManager;
	
	@Autowired
	private WeiXiuManager weiXiuManager;
	
	@Autowired
	private YiJiaoManager yiJiaoManager;
	
	@Autowired
	private BaoFeiManager baoFeiManager;
	
	@Autowired
	private HuanHuoManager huanHuoManager;
	
	@Autowired
	private TuiHuoManager tuiHuoManager;
	
	@Autowired
	private BuPeiManager buPeiManager;
	
	@Autowired
	private ShenQingManager shenQingManager;
	
	@Autowired
	private WuZiManager wuZiManager;
	
	@RequestMapping(value = "/getName")
	public void getName(String userName,HttpServletResponse response){
		User user=userManager.findByUsername(userName);
		PrintWriter out = null;
		response.setContentType("application/json;charset=utf-8");		
		String result="{\"result\":\""+user.getName()+"\"}";
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/getUserByDep")
	public ModelAndView getUserByDep(String depId){
		ModelAndView mav=new ModelAndView();
		mav.addObject("userList", userManager.getUserByDep(depId));
		mav.setViewName("system/userList");
		return mav;
	}
	
	@RequestMapping(value = "/getUserByDep1")
	public ModelAndView getUserByDep1(String depId){
		ModelAndView mav=new ModelAndView();
		mav.addObject("userList", userManager.getUserByDep(depId));
		mav.setViewName("system/userList1");
		return mav;
	}
	
	@RequestMapping(value = "/depUserSetting")
	public ModelAndView depUserSetting() {
		ModelAndView mav=new ModelAndView();
		StringBuilder bs=new StringBuilder();
		bs.append("[");
		List<Dep> list=depManager.getAllDep();
		for(Dep dep:list){
			bs.append("{id:\""+dep.getId()+"\"");
			if(dep.getParent()!=null)
				bs.append(",pId:\""+dep.getParent().getId()+"\"");
			else
				bs.append(",pId:\"0\"");
			bs.append(",name:\""+dep.getDepName()+"\"},");
		}
		bs.delete(bs.length()-1, bs.length());
		bs.append("]");
		String result=bs.toString();
		mav.addObject("result", result);
		mav.setViewName("system/depAndUsers");
		return mav;
	}
	
	@RequestMapping(value = "/getDepUsers")
	public ModelAndView getDepUsers(String id){
		ModelAndView mav=new ModelAndView();
		mav.addObject("userList", userManager.getUsersInDep(id));
		mav.setViewName("system/userListAjax");
		return mav;
	}
	
	@RequestMapping(value = "/getDepDetail")
	public ModelAndView getDepDetail(String id){
		ModelAndView mav=new ModelAndView();
		mav.addObject("depDetail", depManager.get(id));
		mav.setViewName("system/depDetailAjax");
		return mav;
	}
	
	@RequestMapping(value = "/tianJiaXiaJi")
	public ModelAndView tianJiaXiaJi(String id){
		ModelAndView mav=new ModelAndView();
		mav.addObject("pId", id);		
		mav.setViewName("system/editDep");
		return mav;
	}
	
	@RequestMapping(value = "/xiuGaiXX")
	public ModelAndView xiuGaiXX(String id){
		ModelAndView mav=new ModelAndView();
		mav.addObject("id", id);		
		mav.addObject("depDetail", depManager.get(id));
		mav.setViewName("system/editDep");
		return mav;
	}
	
	@RequestMapping(value = "/depSave")
	public void depSave(String pId,Dep dep,HttpServletResponse response){		
		if(!dep.getId().equals("")&&dep.getId()!=null){
			Dep temp=depManager.get(dep.getId());
			temp.setDepName(dep.getDepName());
			temp.setDescription(dep.getDescription());
			depManager.cover(temp);
		}else{
			Dep parent=depManager.get(pId);
			int size=depManager.getChildSize(pId)+1;
			String daiMa=parent.getDaiMa()+String.format("%02d", size);
			while(depManager.getByDaiMa(daiMa)){
				size++;
				daiMa=parent.getDaiMa()+String.format("%02d", size);
			}
			dep.setDaiMa(daiMa);
			dep.setCengJi(parent.getCengJi()+1);
			dep.setParent(parent);
			depManager.save(dep);
		}
		PrintWriter out = null;
		response.setContentType("application/json");
		String result="{\"result\":\"success\"}";
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/addUser")
	public ModelAndView addUser(String depId){
		ModelAndView mav=new ModelAndView();
		mav.addObject("depId", depId);
		mav.addObject("userRoleList", roleManager.getUserRoleList());
		mav.addObject("depList", depManager.getAllDep());
		mav.setViewName("system/editUser");
		return mav;
	}
	
	/*
	 * 2015年11月21日修改
	 * 更换岗位时，查询是否有流程在办，然后调整物资所属部门
	 */
	@RequestMapping(value = "/hasLiuCheng")
	public void hasLiuCheng(User user,HttpServletResponse response){
		String result="{\"result\":\"none\"}";
		response.setContentType("application/json");
		User u=userManager.getUser(user.getId());
		if (hasLiuCheng(u)) {
			result="{\"result\":\"has\"}";
		}
		try {
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean hasLiuCheng(User u) {
		if(shenQingManager.hasLiuCheng(u) || weiXiuManager.hasLiuCheng(u) ||yiJiaoManager.hasLiuCheng(u) || baoFeiManager.hasLiuCheng(u)
			|| huanHuoManager.hasLiuCheng(u) || tuiHuoManager.hasLiuCheng(u) || buPeiManager.hasLiuCheng(u)){
			return true;
		}
		return false;
	}

	@RequestMapping(value = "/user/delete", method = RequestMethod.POST)
	@ResponseBody
	public APIResult deleteUser(String userId) {
		User u=userManager.getUser(userId);
		if (hasLiuCheng(u)) {
			return APIResult.fail("该用户有流程在处理，无法删除");
		}

		userManager.delUser(userId);
		return APIResult.success();
	}
	
	@RequestMapping(value = "/userSave")
	public void addUser(String depId,User user,String roleId,HttpServletResponse response){
		String result="{\"result\":\"success\"}";		
		if(user.getId()!=null&&!user.getId().equals("")){
			User u=userManager.getUser(user.getId());
			Dep dep=depManager.get(depId);
			u.setEmail(user.getEmail());
			u.setName(user.getName());
			u.setDep(dep);
			u.setRole(roleManager.get(roleId));
			u.setUserName(user.getUserName());
			if(u.getRole().getRoleName().equals("部门负责人"))
				u.setGangWei(user.getGangWei());
			else
				u.setGangWei(null);
			userManager.cover(u);
			List<WuZi> wuZiList=wuZiManger.getMyWuZi(user);
			for(WuZi wuZi:wuZiList){
				wuZi.setDep(dep);
				wuZiManger.cover(wuZi);
			}
		}else{
			if(userManager.findByUsername(user.getUserName())!=null){
				result="{\"result\":\"exist\"}";
			}else{
				user.setPassword(user.getUserName());
				user.setDep(depManager.get(depId));
				user.setRole(roleManager.get(roleId));
				if(!user.getRole().getRoleName().equals("部门负责人"))
					user.setGangWei("");
				userManager.save(user);
			}
		}
		PrintWriter out = null;
		response.setContentType("application/json");		
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/xiuGaiUser")
	public ModelAndView xiuGaiUser(String id){
		ModelAndView mav=new ModelAndView();
		mav.addObject("user", userManager.getUser(id));
		mav.addObject("depId", userManager.getUser(id).getDep().getId());
		mav.addObject("depList", depManager.getAllDep());
		mav.addObject("userRoleList", roleManager.getUserRoleList());
		mav.setViewName("system/editUser");
		return mav;
	}
	
	@RequestMapping(value = "/tiaoZhengGangWei")
	public ModelAndView tiaoZhengGangWei(String id){
		ModelAndView mav=new ModelAndView();
		mav.addObject("user", userManager.getUser(id));
		mav.addObject("depList", depManager.getAllDep());
		mav.addObject("userRoleList", roleManager.getUserRoleList());
		mav.setViewName("system/tiaoZhengGangWei");
		return mav;
	}	
	
	@RequestMapping(value = "/tiaoZhengSave")
	public void tiaoZhengSave(String depId,User user,String roleId,HttpServletResponse response){
		String result="{\"result\":\"success\"}";
		User u=userManager.getUser(user.getId());
		u.setDep(depManager.get(depId));
		u.setRole(roleManager.get(roleId));
		userManager.cover(u);
		List<WuZi> list=wuZiManger.getMyWuZi(user);
		for(WuZi wuZi:list){
			wuZi.setDep(depManager.get(depId));
			wuZiManger.cover(wuZi);
		}
		
		toDoManager.deleteList(u.getId());
		
		PrintWriter out = null;
		response.setContentType("application/json");		
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/switchUserCK")
	public void switchUserCK(String id,HttpServletResponse response){
		String result="{\"result\":\"none\"}";
		User user=userManager.getUser(id);		
		if(!user.isLocked()){
			//如果锁定用户，看他是否有流程
			if(wuZiManager.inUseList(user).size()>0){
				result="{\"result\":\"inUse\"}";
			}else if(shenQingManager.hasLiuCheng(user)){
				result="{\"result\":\"has\"}";
			}else if(weiXiuManager.hasLiuCheng(user)){
				result="{\"result\":\"has\"}";
			}else if(yiJiaoManager.hasLiuCheng(user)){
				result="{\"result\":\"has\"}";
			}else if(baoFeiManager.hasLiuCheng(user)){
				result="{\"result\":\"has\"}";
			}else if(huanHuoManager.hasLiuCheng(user)){
				result="{\"result\":\"has\"}";
			}else if(tuiHuoManager.hasLiuCheng(user)){
				result="{\"result\":\"has\"}";
			}else if(buPeiManager.hasLiuCheng(user)){
				result="{\"result\":\"has\"}";
			}
		}
		response.setContentType("application/json");
		try {
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/switchUser")
	public void switchUser(String id,HttpServletResponse response){
		User user=userManager.getUser(id);		
		userManager.lock(user);
		PrintWriter out = null;
		response.setContentType("application/json");
		String result="{\"result\":\"success\"}";
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value= "/passwordCZ")
	public ModelAndView passwordCZ(String id){
		ModelAndView mav=new ModelAndView();
		mav.addObject("userId", id);
		mav.setViewName("system/passwordCZ");
		return mav;
	}
	
	@RequestMapping(value= "/passwordCZSave")
	public void passwordCZSave(String userId,String password,HttpServletResponse response){
		User user=userManager.getUser(userId);
		user.setPassword(password);
		userManager.cover(user);
		PrintWriter out = null;
		response.setContentType("application/json");
		String result="{\"result\":\"success\"}";
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/shanChuBM")
	public void shanChuBM(String id,HttpServletResponse response){
		String result="{\"result\":\"success\"}";
		Dep dep=depManager.get(id);
		if(depManager.hasChild(dep))
			result="{\"result\":\"hasChild\"}";
		else if(userManager.hasUser(dep))
			result="{\"result\":\"hasUser\"}";
		else{
			depManager.delete(dep);
		}
		PrintWriter out = null;
		response.setContentType("application/json");		
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}

	@RequestMapping(value = "/systemEmail")
	public ModelAndView systemEmail(){
		ModelAndView mav=new ModelAndView();
		mav.addObject("email", emailManager.getEmail());
		mav.setViewName("system/systemEmail");
		return mav;		
	}
	
	@RequestMapping(value = "/emailSave")
	public void emailSave(Email temp,HttpServletResponse response){
		if(temp.getId()!=null && !temp.getId().equals("")){
			Email email=temp;
			email.setFromAddress(temp.getFromAddress());
			email.setMailServerHost(temp.getMailServerHost());
			email.setMailServerPort(temp.getMailServerPort());
			email.setPassword(temp.getPassword());
			email.setUserName(temp.getFromAddress());
			emailManager.cover(email);
		}else{
			temp.setUserName(temp.getFromAddress());
			emailManager.save(temp);
		}
		String result="{\"result\":\"success\"}";
		PrintWriter out = null;
		response.setContentType("application/json");		
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/ldap")
	public ModelAndView ldap(){
		ModelAndView mav=new ModelAndView();
		mav.addObject("ldap", ldapManager.getLDAP());
		mav.setViewName("system/ldap");
		return mav;		
	}
	
	@RequestMapping(value = "/ldapSave")
	public void ladpSave(LDAP temp,HttpServletResponse response){
		if(temp.getId()!=null && !temp.getId().equals("")){			
			ldapManager.cover(temp);
		}else{
			ldapManager.save(temp);
		}
		String result="{\"result\":\"success\"}";
		PrintWriter out = null;
		response.setContentType("application/json");		
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/xinYongHu")
	public ModelAndView xinYongHu(){
		ModelAndView mav=new ModelAndView();
		mav.addObject("xinYongHu", userManager.getXinYongHu());
		mav.setViewName("system/xinYongHu");
		return mav;
	}
	
	@RequestMapping(value = "/getTongBuShu")
	public void getTongBuShu(HttpServletResponse response){
		int zongShu=0;
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser.hasRole("固资管理员")){
			zongShu+=userManager.getXinYongHu().size();
		}
		PrintWriter out = null;
		response.setContentType("application/json;charset=utf-8");		
		String result="{\"result\":\"("+zongShu+")\"}";
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping(value = "/deleteUser")
	public void deleteUser(String id,HttpServletResponse response){
		User user=userManager.getUser(id);
		userManager.lock(user);
		toDoManager.deleteList(id);
		PrintWriter out = null;
		response.setContentType("application/json");
		String result="{\"result\":\"success\"}";
		try {
			out = response.getWriter();
			out.write(result);
		} catch (Exception e) {
		}
	}

	@RequestMapping(value = "/toChangeUserDep", method = RequestMethod.GET)
	private ModelAndView toChangeUserDep(@RequestParam(value = "userIds") String userIds) {
		ModelAndView mav=new ModelAndView();
		mav.addObject("userIds", userIds);
		mav.addObject("depList", depManager.getAllDep());
		mav.setViewName("system/changeUserDep");
		return mav;
	}

	@RequestMapping(value = "/changeUserDep", method = RequestMethod.POST)
	@ResponseBody
	public APIResult changeUserDep(@RequestParam(value = "userIds") String userIds, @RequestParam(value = "depId") String depId) {
		if (StringUtils.hasText(userIds)) {
			String[] userIdArray = userIds.split(",");
			Dep dep = depManager.get(depId);
			if (dep != null) {
				User user = null;
				for (String userId : userIdArray) {
					user = userManager.getUser(userId);
					user.setDep(dep);
					userManager.cover(user);

					wuZiManager.updateDepByUserId(user);
				}
			}
		}
		return APIResult.success();
	}
}
